package com.xuxueli.applyModules.commont;
import com.xuxueli.applyModules.exception.ErrorException;
import com.xuxueli.applyModules.exception.SourceException;
import com.xuxueli.applyModules.exception.TokenException;
import com.xuxueli.applyModules.utils.CommonResult;
import com.xuxueli.applyModules.utils.R;
import org.omg.CORBA.portable.ApplicationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * 全局异常捕捉
 */
@RestControllerAdvice
public class GlobalExceptionHandler  {

    @ExceptionHandler(ErrorException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    R errorException(ErrorException err){
        return R.error(err.getCode(),err.getMessage());
    }

    @ExceptionHandler(TokenException.class)
    ResponseEntity toeknException(TokenException err){
        R error = R.error(err.getCode(), err.getMessage());
        if("401".compareTo(String.valueOf(err.getCode()))==0){
            return new ResponseEntity<>(error, HttpStatus.UNAUTHORIZED);
        }else{
            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
        }
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResult handleValidationException(ConstraintViolationException e) {
        for (ConstraintViolation<?> s : e.getConstraintViolations()) {
            return CommonResult.validateFailed(s.getMessage());
        }
        return CommonResult.validateFailed();
    }

    @ExceptionHandler(ApplicationException.class)
    @ResponseStatus(HttpStatus.OK)
    public CommonResult handleApplicationException(ApplicationException applicationException) {
        return CommonResult.validateFailed(applicationException.getMessage());
    }

    @ExceptionHandler(SourceException.class)
    @ResponseStatus(HttpStatus.OK)
    public CommonResult handleSourceException(SourceException sourceException) {
        return CommonResult.validateFailed(sourceException.getMessage());
    }


}
